package com.itchu.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", HttpServletResponse.SC_UNAUTHORIZED);

        if (e instanceof AccountExpiredException) {
            //账号过期
            map.put("message", "账号过期！");
        } else if (e instanceof BadCredentialsException) {
            //密码错误
            map.put("message", "密码错误！");
        } else if (e instanceof CredentialsExpiredException) {
            //密码过期
            map.put("message", "密码过期！");
        } else if (e instanceof DisabledException) {
            //账号不可用
            map.put("message", "账号不可用！");
        } else if (e instanceof LockedException) {
            //账号锁定
            map.put("message", "账号被锁定！");
        } else if (e instanceof InternalAuthenticationServiceException) {
            //用户不存在
            map.put("message", "用户名或密码错误");
        }else{
            //其他错误
            map.put("message", "其他错误！");
        }
        // 设置返回的编码格式，防止乱码
        response.setContentType("application/json;charset=utf-8");
        // 401错误
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // 以字符输出流响应回去
        try {
            PrintWriter out = response.getWriter();
            out.write(new ObjectMapper().writeValueAsString(map));
            out.flush();
            out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}